package com.ling.sdk.http

import com.ling.sdk.app.App
import com.ling.sdk.utils.NetworkUtil
import rx.Observer
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

class ApiObserver<T : ApiResponseBean>(private val callBack: ApiCallBack<T>) : Observer<T> {
    var responseCode = -1
    override fun onNext(responseBean: T) {
        if (200 != responseBean.status) {
            responseCode = -1
            callBack.onError(responseBean.status.toString(), responseBean.desc)
            return
        }
        responseCode = 0
        callBack.onSuccess(responseBean)
        return
    }

    override fun onError(e: Throwable?) {
        e?.printStackTrace()
        when {
            e is UnknownHostException || e is ConnectException -> callBack.onError(HttpStatus.UNKONW_SERVER_ERROR.CODE)
            e is SocketTimeoutException -> callBack.onError(HttpStatus.SERVER_TIME_OUT.CODE)
            //有网情况服务器错误
            e is retrofit2.HttpException || NetworkUtil.isConnected(App.app) && responseCode == -1 -> callBack.onError(HttpStatus.SERVER_ERROR.CODE)
            //有网络情况，返回响应正常，内部app异常
            NetworkUtil.isConnected(App.app) && responseCode == 0 -> callBack.onError(HttpStatus.APP_EXCEPTION.CODE)
            else -> callBack.onError(HttpStatus.NET_ERROR.CODE)
        }
    }

    override fun onCompleted() {
        callBack.onCompleted()
    }

}